package com.ecar.core.common.entity;

import com.ecar.core.common.entity.Privilege;
import com.ecar.core.common.entity.EcarUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * Created by 30 on 2016/4/20.
 */
public class SecurityUserDetails implements UserDetails {

	protected static final String ROLE_PREFIX = "ROLE_";
//	protected static final GrantedAuthority DEFAULT_USER_ROLE = new SimpleGrantedAuthority(ROLE_PREFIX + Privilege
//			.PRIVILEGE_USER);

	protected EcarUser ecarUser;
	
	protected Set<String> privileges;

	protected List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

	public SecurityUserDetails() {
	}

	public SecurityUserDetails(EcarUser ecarUser,Set<String> privileges) {
		this.ecarUser = ecarUser;
		this.privileges=privileges;
		initialAuthorities();
	}

	private void initialAuthorities() {
		this.grantedAuthorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + Privilege.CLIENT));
		for (String privilege : privileges) {
			this.grantedAuthorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + privilege));
		}
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		return this.grantedAuthorities;
	}

	@Override
	public String getPassword() {
		return ecarUser.getPassword();
	}

	@Override
	public String getUsername() {
		return ecarUser.getUsername();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}
